package com.nebula.service.Impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nebula.common.Const;
import com.nebula.common.ServerResponse;
import com.nebula.mapper.FilesMapper;
import com.nebula.mapper.FoldersMapper;
import com.nebula.mapper.UrlShareMapper;
import com.nebula.pojo.UrlShare;
import com.nebula.service.IFileAndFolderShareService;
import com.nebula.util.ExtractKeyUtil;
import com.nebula.util.PageUtil;
import com.nebula.vo.UrlShareListVo;

@Service("fileAndFolderShareService")
public class FileAndFolderShareServiceImpl implements IFileAndFolderShareService {
	
	@Autowired
	private UrlShareMapper urlShareMapper;
	@Autowired
	private FilesMapper filesMapper;
	@Autowired
	private FoldersMapper foldersMapper;
	
	public ServerResponse getShareURLAndKey(String valArr,String username,String title,String failtime,String type){
		String URL = "/nebula/share/init.action";
		Map<String, String> map = Maps.newHashMap();
		String Key = "";
		String surl = "";
		if("private".equals(type)){
			Key = checkKey(ExtractKeyUtil.getKey(4));
			surl = checkShortUrl(ExtractKeyUtil.getKey(7));
			
			URL += "?surl=" + surl;
			map.put("URL", URL);
			map.put("KEY", Key);
		}else{
			Key = "";
			surl = checkShortUrl(ExtractKeyUtil.getKey(7));
			
			URL += "?surl=" + surl;
			
			map.put("URL", URL);
			map.put("KEY", Key);
		}
		
		UrlShare urlShare = new UrlShare();
		urlShare.setDownloads(0);
		urlShare.setSaveTimes(0);
		urlShare.setViewed(0);
		urlShare.setTitle(title);
		urlShare.setFailureTime(failtime);
		urlShare.setUsername(username);
		urlShare.setFileIdGroup(valArr);
		urlShare.setFileKey(Key);
		urlShare.setLink(URL);
		urlShare.setShortUrl(surl);
		if("".equals(Key)){
			urlShare.setType("public");
		}else{
			urlShare.setType("private");
		}
		
		int resultCount = urlShareMapper.insert(urlShare);
		if(resultCount > 0){
			return ServerResponse.createBySuccess(map);
		}
		return ServerResponse.createByErrorMessage("创建私密链接失败");
	}
	
	public ServerResponse getInitInfo(String surl){
		UrlShare urlShare = urlShareMapper.selectInitInfo(surl);
		if(urlShare != null){
			return ServerResponse.createBySuccess(urlShare);
		}
		return ServerResponse.createByErrorMessage("短地址不存在");
	}
	
	public UrlShareListVo getUrlShareInfo(UrlShare urlShare){
		UrlShareListVo urlShareListVo = assembleurlShareListVo(urlShare);
		UrlShare viewed = new UrlShare();
		viewed.setId(urlShare.getId());
		viewed.setViewed(urlShare.getViewed() + 1);
		urlShareMapper.updateByPrimaryKeySelective(viewed);
		return urlShareListVo;
	}
	
	public ServerResponse<String> updateSaveTimes(String surl){
		ServerResponse responseServer = this.getInitInfo(surl);
		if(responseServer.isSuccess()){
			UrlShare urlShare = (UrlShare) responseServer.getData();
			UrlShare saveTimes = new UrlShare();
			saveTimes.setId(urlShare.getId());
			saveTimes.setSaveTimes(urlShare.getSaveTimes() + 1);
			int resultCount = urlShareMapper.updateByPrimaryKeySelective(saveTimes);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("更新保存次数成功");
			}
		}
		return ServerResponse.createByErrorMessage("更新保存次数失败");
	}
	
	public ServerResponse<String> updateDownloads(String surl){
		ServerResponse responseServer = this.getInitInfo(surl);
		if(responseServer.isSuccess()){
			UrlShare urlShare = (UrlShare) responseServer.getData();
			UrlShare downloads = new UrlShare();
			downloads.setId(urlShare.getId());
			downloads.setDownloads(urlShare.getDownloads() + 1);
			int resultCount = urlShareMapper.updateByPrimaryKeySelective(downloads);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("更新下载次数成功");
			}
		}
		return ServerResponse.createByErrorMessage("更新下载次数失败");
	}

	public ServerResponse<String> cancelShare(String surl){
		UrlShare urlShare = urlShareMapper.selectInitInfo(surl);
		int	resultCount = urlShareMapper.deleteByPrimaryKey(urlShare.getId());
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("取消外链分享成功");
		}
		return ServerResponse.createByErrorMessage("取消外链分享失败");
	}
	
	public ServerResponse<String> cancelShareByIdGroup(String groupId){
		String []str = groupId.split(",");
		List<Integer> list = Lists.newArrayList();
		Map<String, List<Integer>> map = Maps.newHashMap();
		for(int i = 0,len = str.length;i < len;i++){
			list.add(Integer.parseInt(str[i]));
		}
		map.put("id", list);
		int resultCount = urlShareMapper.deleteByPrimartKeyMap(map);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("取消外链分享成功");
		}
		return ServerResponse.createByErrorMessage("取消外链分享失败");
	}
	
	public ServerResponse<List<UrlShareListVo>> privateShareInfo(String username){
		List<UrlShare> list = urlShareMapper.selectByUsername(username);
		List<UrlShareListVo> urlShareListVos = Lists.newArrayList();
		for(UrlShare urlShare : list){
			UrlShareListVo urlShareListVo = assembleurlShareListVo(urlShare);
			urlShareListVos.add(urlShareListVo);
		}
		return ServerResponse.createBySuccess(urlShareListVos);
	}
	
	public ServerResponse<List<UrlShareListVo>> publicShareInfo(Integer pageNum,Integer pageSize
			,HttpServletRequest request){
		List<UrlShareListVo> urlShareListVos = Lists.newArrayList();
		
		PageHelper.startPage(pageNum, pageSize);
		List<UrlShare> list = urlShareMapper.selectPublicList();
		for(UrlShare urlShare : list){
			UrlShareListVo urlShareListVo = assembleurlShareListVo(urlShare);
			urlShareListVos.add(urlShareListVo);
		}
		
		PageInfo<UrlShare> pageInfo = new PageInfo<UrlShare>(list);
		Map<String, Object> info = PageUtil.pageInfo(pageInfo);
		
		request.setAttribute("pageInfo", info);
		
		return ServerResponse.createBySuccess(urlShareListVos);
	}
	
	public ServerResponse<List<UrlShareListVo>> searchPublicShareInfo(Integer pageNum,Integer pageSize
			,String queries,HttpServletRequest request){
		List<UrlShareListVo> urlShareListVos = Lists.newArrayList();
		
		PageHelper.startPage(pageNum, pageSize);
		List<UrlShare> list = urlShareMapper.searchPublicList(queries);
		for(UrlShare urlShare : list){
			UrlShareListVo urlShareListVo = assembleurlShareListVo(urlShare);
			urlShareListVos.add(urlShareListVo);
		}
		
		PageInfo<UrlShare> pageInfo = new PageInfo<UrlShare>(list);
		Map<String, Object> info = PageUtil.pageInfo(pageInfo);
		
		request.setAttribute("pageInfo", info);
		
		return ServerResponse.createBySuccess(urlShareListVos);
	}
	
	private String checkKey(String key){
		int resultCount = urlShareMapper.checkKey(key);
		if(resultCount > 0){
			key = ExtractKeyUtil.getKey(4);
			checkKey(key);
		}
		return key;
	}
	
	private String checkShortUrl(String surl){
		int resultCount = urlShareMapper.checkShortUrl(surl);
		if(resultCount > 0){
			surl = ExtractKeyUtil.getKey(7);
			checkShortUrl(surl);
		}
		return surl;
	}
	
	private UrlShareListVo assembleurlShareListVo(UrlShare urlShare){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			
		String []imgTypes = {"jpg","jpeg","gif","png","bmp"};
		String []musicTypes = {"mp3","wav","wma","flac","ape","aac","ogg"};
		String []zipTypes = {"rar","zip","7z","iso","cab","arj","jar","rar5"};
		String []vedioTypes = {"avi","wmv","mpeg","mp4","mov","mkv","flv","f4v","m4v","rmvb",
				"rm","3gp","dat","ts","mts","vob"};
		
		String []str = urlShare.getFileIdGroup().split(",");
		int fileCount = 0 , folderCount = 0 , allFolder = 0 , allFile = 0;
		boolean isDelete = false;
		
		for(int i = 0,len = str.length;i < len;i++){
			if(str[i].length() <= 11){
				allFolder += 1;
				folderCount = foldersMapper.selectFolderCountByPrimaryKey(Integer.parseInt(str[i]));
				if(folderCount == 0) break;
			}else if(str[i].length() == 15){
				allFile += 1;
				fileCount = filesMapper.selectFileCountByPrimaryKey(Long.parseLong(str[i]));
				if(fileCount == 0) break;
			}
		}
		
		UrlShareListVo urlShareListVo = new UrlShareListVo();
		urlShareListVo.setId(urlShare.getId());
		urlShareListVo.setSharingTime(sdf.format(urlShare.getSharingTime()));
		urlShareListVo.setFileIdGroup(urlShare.getFileIdGroup());
		urlShareListVo.setUsername(urlShare.getUsername());
		
		if(allFolder > 0 && allFile > 0){
			if(fileCount == 0 || folderCount == 0) isDelete = true;
		}else if(allFolder > 0 && allFile == 0){
			if(folderCount == 0) isDelete = true;
		}else if(allFolder == 0 && allFile > 0){
			if(fileCount == 0) isDelete = true;
		}
		
		if(isDelete){
			if(!"文件已被删除".equals(urlShare.getFailureTime())){
				UrlShare urlShare1 = new UrlShare();
				urlShare1.setFailureTime("文件已被删除");
				urlShare1.setId(urlShare.getId());
				urlShareMapper.updateByPrimaryKeySelective(urlShare1);
			}
			urlShareListVo.setTitle(Const.FILE_DELETED);
			urlShare.setFailureTime(Const.FAILURE);
		}else{
			if(Const.FAILURE.equals(urlShare.getFailureTime())){
				urlShareListVo.setTitle(Const.OVERDUE);
			}else{
				urlShareListVo.setTitle(urlShare.getTitle());
			}
		}
		
		if(Const.PERMANENT.equals(urlShare.getFailureTime()) || Const.FAILURE.equals(urlShare.getFailureTime())){
			urlShareListVo.setFailureTime(urlShare.getFailureTime());
		}else{
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(urlShare.getSharingTime());
			calendar.add(Calendar.DATE, Integer.parseInt(urlShare.getFailureTime()));
			Date failureTime = calendar.getTime();
			Map<String, Object> map = Maps.newHashMap();
			map.put("failureTime",failureTime);
			map.put("id",urlShare.getId());
			
			if("1".equals(urlShare.getFailureTime())){
				int hour = urlShareMapper.selectTimesTampDiffHour(map);
				if(hour > 0){
					int minute = urlShareMapper.selectTimesTampDiffMinute(map);
					if(minute - hour * 60 >= 30){
						urlShareListVo.setFailureTime(hour + 1 + "小时后");
					}else{
						urlShareListVo.setFailureTime(hour + "小时后");
					}
				}else{
					int minute = urlShareMapper.selectTimesTampDiffMinute(map);
					if(minute > 0){
						urlShareListVo.setFailureTime(minute + "分钟后");
					}else{
						urlShareListVo.setFailureTime(Const.FAILURE);
					}
				}
			}else if("7".equals(urlShare.getFailureTime())){
				int day = urlShareMapper.selectTimesTampDiffDay(map);
				int hour = urlShareMapper.selectTimesTampDiffHour(map);
				int minute = urlShareMapper.selectTimesTampDiffMinute(map);
				if(day > 0){
					if(hour - day * 24 > 0 || minute - hour * 60 > 0){
						urlShareListVo.setFailureTime(day + 1 + "天后");
					}else{
						urlShareListVo.setFailureTime(day + "天后");
					}
				}else{
					if(hour > 0){
						if(minute - hour * 60 > 0){
							urlShareListVo.setFailureTime(hour + 1 + "小时后");
						}else{
							urlShareListVo.setFailureTime(hour + "小时后");
						}
					}else{
						if(minute > 0){
							urlShareListVo.setFailureTime(minute + "分钟后");
						}else{
							urlShareListVo.setFailureTime(Const.FAILURE);
							urlShareListVo.setTitle(Const.OVERDUE);
						}
					}
				}
			}
		}
		
		urlShareListVo.setShortUrl(urlShare.getShortUrl());
		urlShareListVo.setLink(urlShare.getLink());
		urlShareListVo.setViewed(urlShare.getViewed());
		urlShareListVo.setDownloads(urlShare.getDownloads());
		urlShareListVo.setSave_times(urlShare.getSaveTimes());
		urlShareListVo.setFileKey(urlShare.getFileKey());
		urlShareListVo.setType(urlShare.getType());
		
		if(str.length > 1){
			urlShareListVo.setIcon("/nebula/" + Const.MULTI_ICON);
		}else if(str.length == 1){
			if(str[0].length() <= 11){
				urlShareListVo.setIcon("/nebula/" + Const.FOLDER_ICON);
			}else if(str[0].length() == 15){
				String title = urlShare.getTitle();
				String lowercaseSuffix = title.substring(title.lastIndexOf(".") + 1).toLowerCase().trim();
				
				//图片
				for(String type : imgTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						urlShareListVo.setIcon("/nebula/" + Const.IMG_ICON);
						break;
					}
				}
				
				//音乐
				for(String type : musicTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						urlShareListVo.setIcon("/nebula/" + Const.MUSIC_ICON);
						break;
					}
				}
				
				//压缩文件
				for(String type : zipTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						urlShareListVo.setIcon("/nebula/" + Const.ZIP_ICON);
						break;
					}
				}
				
				//视频文件
				for(String type : vedioTypes){
					if(lowercaseSuffix.indexOf(type) > -1){
						urlShareListVo.setIcon("/nebula/" + Const.VEDIO_ICON);
						break;
					}
				}
				
				if(urlShareListVo.getIcon() == null || urlShareListVo.getIcon().equals("")){
					if("apk".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.APK_ICON);
					}
					else if("torrent".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.BT_ICON);
					}
					else if("pdf".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.PDF_ICON);
					}
					else if("xls".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.XLS_ICON);
					}
					else if("txt".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.TXT_ICON);
					}
					else if("exe".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.EXE_ICON);
					}
					else if("folder".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.FOLDER_ICON);
					}
					else if("doc".equals(lowercaseSuffix) || "docx".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.DOC_ICON);
					}
					else if("ppt".equals(lowercaseSuffix) || "pptx".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.PPT_ICON);
					}
					else if("vsd".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.VSD_ICON);
					}
					else if("html".equals(lowercaseSuffix)){
						urlShareListVo.setIcon("/nebula/" + Const.HTML_ICON);
					}
					else {
						urlShareListVo.setIcon("/nebula/" + Const.UNKNOWN_ICON);
					}
				}
			}
		}
		return urlShareListVo;
	}
}
